import lombok.Getter;
import java.util.*;

/**
 * @author xhw
 */

@Getter
public class DataGroups {
    //这个类是一个数据表，包含了要被聚合的行属性和列属性

    //property
    private final List<String> rowGroupAttributes;
    private final List<String> columnGroupAttributes;

    public DataGroups(List<String> rowGroupAttributes, List<String> columnGroupAttributes) {
        this.rowGroupAttributes = rowGroupAttributes;
        this.columnGroupAttributes = columnGroupAttributes;
    }

    public DataGroups() {
        this.rowGroupAttributes = new ArrayList<>();
        this.columnGroupAttributes = new ArrayList<>();
    }

    //设置一个treeMap来存储值
    private final Map<GroupKey, List<DataRow>> groups = new TreeMap<>();

    public void addDataRow(DataRow row) {
        //添加数据行
        List<String> rows = rowGroupAttributes.stream().map(row::getValue).toList();
        List<String> columns = columnGroupAttributes.stream().map(row::getValue).toList();
        //添加数据
        //进行行类分株
        GroupKey key = new GroupKey(rows, columns);
        //添加数据值
        groups.computeIfAbsent(key, k -> new ArrayList<>()).add(row);

    }

    public Set<GroupKey> getGroupKeys() {
        return groups.keySet();
    }

    public Map<GroupKey, Number> caculateValues(Aggregation aggregation) {
        Map<GroupKey, Number> result = new HashMap<>();
        groups.forEach((key, value) -> {
            List<Number> values = value.stream().map(row -> row.getValue(aggregation.getColumn()))
                    .map(Integer::parseInt)
                    .map(Number.class::cast).toList();
            //计算值
            AggregationValues aggregationValues = new AggregationValues(aggregation.getCalType(), values);
            result.put(key, aggregationValues.calculate());

        });
        return result;
    }
}
